﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Urs.Admin.Models.Users;
using Urs.Admin.Models.Security;
using Urs.Core;
using Urs.Data.Domain.Users;
using Urs.Data.Domain.Security;
using Urs.Services.Users;
using Urs.Services.Localization;
using Urs.Services.Logging;
using Urs.Services.Security;
using Urs.Framework.Controllers;
using Urs.Admin.Models.Common;

namespace Urs.Admin.Controllers
{
    [AdminAuthorize]
    public partial class SecurityController : BaseAdminController
    {
        #region Fields

        private readonly ILogger _logger;
        private readonly IWorkContext _workContext;
        private readonly IPermissionService _permissionService;
        private readonly IUserService _userService;
        private readonly ILocalizationService _localizationService;

        #endregion

        #region Constructors

        public SecurityController(ILogger logger, IWorkContext workContext,
            IPermissionService permissionService,
            IUserService userService, ILocalizationService localizationService)
        {
            this._logger = logger;
            this._workContext = workContext;
            this._permissionService = permissionService;
            this._userService = userService;
            this._localizationService = localizationService;
        }

        #endregion

        #region Methods

        public IActionResult Unauthorized(string pageUrl)
        {
            var currentUser = _workContext.CurrentUser;
            if (currentUser == null || currentUser.IsGuest())
            {
                _logger.Information(string.Format("Access denied to anonymous request on {0}", pageUrl));
                return View();
            }

            _logger.Information(string.Format("Access denied to user #{0} '{1}' on {2}", currentUser.Email, currentUser.Email, pageUrl));


            return View();
        }

        public IActionResult Permissions()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAcl))
                return HttpUnauthorized();

            var model = new PermissionMappingModel();

            var permissionRecords = _permissionService.GetAllPermissionRecords();
            var customerRoles = _userService.GetAllUserRoles(true);
            var group = _permissionService.GetAllGroup();
            foreach (var pr in permissionRecords)
            {
                model.AvailablePermissions.Add(new PermissionRecordModel()
                {
                    Name = pr.Name,
                    SystemName = pr.SystemName
                });
            }
            foreach (var cr in customerRoles)
            {
                model.AvailableUserRoles.Add(new UserRoleModel()
                {
                    Id = cr.Id,
                    Name = cr.Name
                });
            }
            model.AvailableGroup.Add(new SelectListItem() { Text = "—请选择—" });
            foreach (var g in group)
            {
                model.AvailableGroup.Add(new SelectListItem()
                {
                    Value = g,
                    Text = _localizationService.GetResource(g)
                });
            }
            var mappings = _permissionService.GetPermissionRecordUserMappings();

            foreach (var pr in permissionRecords)
                foreach (var cr in customerRoles)
                {
                    var count = mappings.Where(q => q.UserRoleId == cr.Id && q.PermissionRecordId == pr.Id).Count();
                    bool allowed = count > 0;
                    //bool allowed = pr.CustomerRoles.Where(x => x.CustomerRoleId == cr.Id).Count() > 0;
                    if (!model.Allowed.ContainsKey(pr.SystemName))
                        model.Allowed[pr.SystemName] = new Dictionary<int, bool>();
                    model.Allowed[pr.SystemName][cr.Id] = allowed;
                }

            return View(model);
        }


        [HttpPost]
        public IActionResult PermissionsEnabled(CheckboxValueModel checkbox)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAcl))
                return HttpUnauthorized();

            var pr = _permissionService.GetPermissionRecordBySystemName(checkbox.Value);
            var cr = _userService.GetUserRoleById(checkbox.Id);

            if (pr == null || cr == null)
                return Json(new { error = 1 });

            if (checkbox.Checked)
            {
                if (pr.UserRoles.Where(x => x.UserRoleId == checkbox.Id).FirstOrDefault() == null)
                {
                    pr.UserRoles.Add(new PermissionRecordUserMapping() { UserRole = cr });
                    _permissionService.UpdatePermissionRecord(pr);
                }
            }
            else
            {
                if (pr.UserRoles.Where(x => x.UserRoleId == cr.Id).FirstOrDefault() != null)
                {
                    pr.UserRoles.Remove(pr.UserRoles.FirstOrDefault(x => x.UserRoleId == cr.Id));
                    _permissionService.UpdatePermissionRecord(pr);
                }
            }
            return Json(new { success = 1 });
        }

        #endregion
    }
}
